package com.wink.admin.utils;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.util.ObjectUtil;
import com.wink.admin.filter.RepeatedlyRequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * request工具类
 *
 * @author xw
 * @date 2020-11-03 14:07
 */
public class RequestUtils {

    private static final Logger logger = LoggerFactory.getLogger(RequestUtils.class);


    /**
     * 获取所有的请求头
     *
     * @param request
     * @return
     */
    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> headerMap = new HashMap<>();
        List<String> headers = ListUtil.toList();
        headers.add("Postman-Token");
        headers.add("Proxy-Connection");
        headers.add("X-Lantern-Version");
        headers.add("Cookie");
        headers.add("Accept-Encoding");
        headers.add("Connection");
        headers.add("Accept");
        headers.add("Content-Type");
        headers.add("Content-Length");


        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            if (headers.contains(headerName)) {
                continue;
            }
            headerMap.put(headerName, request.getHeader(headerName));
        }
        return headerMap;
    }

    /**
     * 从Request中获取所有的请求参数，包括GET/POST/PATCH等请求，包括路径参数
     *
     * @param request
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @author xw
     * @date 2020/11/3 15:44
     */
    public static Map<String, Object> getRequestParameter(HttpServletRequest request) {
        Map<String, Object> paramMap = new HashMap<>(16);

        // URL请求参数
        Map<String, String> uriTemplateVar = getUrlValue(request);
        if (ObjectUtil.isNotEmpty(uriTemplateVar)) {
            logger.info("getUriTemplateVar:{}", JsonUtil.toStr(uriTemplateVar));
            paramMap.putAll(uriTemplateVar);
        }

        // body
        //当为POST请求且 application/json时，request被RequestFilter处理为wrapper类
        if (request instanceof RepeatedlyRequestWrapper) {
            RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request;
            String bodyString = getBodyString(repeatedlyRequest);
            // 该方法为了避免 反序列化多层json时，改变对象顺序
            Map<String, Object> bodyMap = JsonUtil.toLinkedHashMap(bodyString);
            if (ObjectUtil.isNotEmpty(bodyMap)) {
                paramMap.putAll(bodyMap);
            }
            return paramMap;
        } else {
            // 表单传参
            Map<String, String[]> parameterMap = request.getParameterMap();
            paramMap.putAll(parameterMap);
        }

        return paramMap;
    }


    /**
     * 获取请求的路径参数
     *
     * @param request
     * @return
     */
    public static Map<String, String> getUrlValue(HttpServletRequest request) {
        NativeWebRequest webRequest = new ServletWebRequest(request);
        Map<String, String> uriTemplateVars = (Map<String, String>) webRequest.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);

        return uriTemplateVars;
    }

    /**
     * 获得url中参数
     *
     * @param url
     * @return
     */
    public static Map<String, String> getUrlValue(String url) {
        Map<String, String> map = new HashMap<>();

        url = URLDecoder.decode(url, StandardCharsets.UTF_8);
        if (url.indexOf('?') != -1) {
            final String contents = url.substring(url.indexOf('?') + 1);
            String[] keyValues = contents.split("&");
            for (int i = 0; i < keyValues.length; i++) {
                String key = keyValues[i].substring(0, keyValues[i].indexOf("="));
                String value = keyValues[i].substring(keyValues[i].indexOf("=") + 1);
                map.put(key, value);
            }
        }

        return map;
    }

    /**
     * 获取Body内容
     *
     * @param request
     * @return bodyStr
     */
    public static String getBodyString(ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try (InputStream inputStream = request.getInputStream()) {
            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            logger.warn("getBodyString出现问题！");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("读取requestInputStream异常：", e);
                }
            }
        }
        logger.info("请求的body内容为:{}", sb.toString());
        return sb.toString();
    }


}
